
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Text {
	final static Charset ENCODING = StandardCharsets.ISO_8859_1;
	static final String HTML_FILE = "..\\index.html";

	static String removeRegEx[];
	static String replaceRegEx[];
	static String replaceWithRegEx[];
	
	static int slideNo = 1;

	public static void main(String args[]) {
		String folder = "..\\audio\\"; // Captions directory
		// String outFile = "voice-text.txt"; // merger of all Captions

		try {

			List<String> text = new Vector<String>();
			File[] txtFiles = getCaptionFiles(folder);

			// Fil the RegEx patterns for Voice XML
			fillRegEx();

			// text.add("<div class=\"lesson\">");
			//text.add("<h2>Voice Text</h2>");
			
			// Read all the captions into text
			String temp = "";
			for (int i = 0; i < txtFiles.length; i++) {
				temp = read(txtFiles[i]);
				//System.out.println(temp);
				text.add(temp);
			}
			
			//text.add("\n<p>***** End of Voice *****</p>\n");
		
			// add necessary HTML
			//List<String> html = addHTML(text);

			writeCaptionsToIndexHTML(text);

		} catch (IOException e) {
			print("error : " + e.toString());
		}

	}

	private static File[] getCaptionFiles(String folder) {
		File f = new File(folder);

		FilenameFilter audioFilter = new FilenameFilter() {
			public boolean accept(File dir, String name) {
				String regEx = "audio-?\\d?\\d?\\.txt";
				return (name.matches(regEx));
			}
		};

		File[] files = f.listFiles(audioFilter);

		return files;
	}

	private static String read(File file) throws IOException {
		print("Reading from file. " + file.getName());

		List<String> list = Files.readAllLines(file.toPath(), ENCODING);

		String temp = "";
		
		// Process a single line
		for (String s : list) {

			// print("Processing token -> " + s);
			if (!remove(s)) {
				
				// add <br/> tag if required
				// and add into output
				temp = temp + "\n" + addBrTag(s);
			}else {
				// Removed
				//System.out.println(s);
			}
			
			/*if(s.trim().length() == 0){
				temp = temp + "<br/>";
			}*/
		}

		// temp = temp + "\n</p>";

		temp = replace (temp);
		
		// temp = "<br/><div class=\"caption\" " + "id=\"caption" + slideNo + "\"" +">" + "<br/><br/>" + temp + "</div><br/>\n";
		temp = "<br/><div class=\"caption\" " + "id=\"caption" + slideNo + "\"" +">" + temp + "</div><br/>\n";
		
		slideNo++;
		
		return temp;
	}
	
	static String addBrTag(String line){
		
		// Check empty line
		if(line.trim().length() == 0){
			line = line + "<br/>";
		
		// check . at end of line before \n
		}else if(line.endsWith(".") || line.endsWith("?") || line.endsWith(":")) {
			line = line + "<br/>";
		}
		return line;
	}
	
	/*static List<String> addHTML(List<String> text) {
		List<String> updatedText = new Vector<String>();

		// add <br/>
		for (String s : text) {
			
			if (!isHTML(s)) {
				updatedText.add(s);
			} else {
				updatedText.add(s + "<br/>");
			}
		}

		return updatedText;
	}*/

	private static boolean remove(String text) {
		Pattern p;
		Matcher m;
		boolean b = false;

		for (int i = 0; i < removeRegEx.length; i++) {
			p = Pattern.compile(removeRegEx[i]);
			m = p.matcher(text);
			b = m.matches();
			if (b)
				break;
		}

		// print (" Ignored = " + b);

		return b;
	}

	private static String replace(String text) {
		String out = text;

		for (int i = 0; i < replaceRegEx.length; i++) {

			out = Pattern.compile(replaceRegEx[i]).matcher(out).replaceAll(replaceWithRegEx[i]);
		}

		return out;
	}

	private static void fillRegEx() {
		Vector<String> removeList = new Vector<String>(); // remove RegEx list

		Vector<String> replaceRegExList = new Vector<String>(); // replace RegEx list
		Vector<String> replaceWithRegExList = new Vector<String>(); // replace with

		// Remove list

		// final String NL = System.getProperty("line.separator");

		// Slide title - <slide id="Slide 1" />
		removeList.add("(<slide)(.*)(>)");

		// <volume level="100">
		removeList.add("<volume level=\".*\">");

		// <pitch absmiddle="0">
		removeList.add("<pitch absmiddle=\".*\">");

		// <rate absspeed="0">
		removeList.add("<rate absspeed=\".*\">");

		// <voice required="name = VW Paul">
		removeList.add("<voice required=\".*\">");

		// <voice required="name = VW Paul">
		removeList.add("</voice>");

		// ******************************************************************************************************************************
		// Replace list

		// <silence msec="nnn"/>
		//replaceRegExList.add("<silence\\smsec=\"\\d{1,}\"/>");
		//replaceWithRegExList.add(";");

		// <spell>
		//replaceRegExList.add("<spell>");
		//replaceWithRegExList.add("");

		// <spell>
		//replaceRegExList.add("</spell>");
		//replaceWithRegExList.add("");
		
		// Corrections
		replaceRegExList.add("\\sofun");
		replaceWithRegExList.add(" often");

		removeRegEx = new String[removeList.size()];
		replaceRegEx = new String[replaceRegExList.size()];
		replaceWithRegEx = new String[replaceWithRegExList.size()];

		removeList.copyInto(removeRegEx);
		replaceRegExList.copyInto(replaceRegEx);
		replaceWithRegExList.copyInto(replaceWithRegEx);
	}

	static void writeCaptionsToIndexHTML(List<String> textToAdd) {
		if (Util.isNullObject(textToAdd)){
			print("Noting To Add");
			return;
		}
		print("Writing Captions to Index file...");
		//print(textToAdd);
		if (textToAdd.size() < 1)
			return;
		
		// Convert list to String
		String strTextToAdd = "";
		
		for (String s: textToAdd){
			strTextToAdd = strTextToAdd + "\n" + s;
		}
		
		try {
			File file = new File(HTML_FILE);
			List<String> list = Files.readAllLines(file.toPath(), ENCODING);
			//print("index file lines = " + list.size());
			
			if (list.size() < 100) {
				print("Index HTML file is not Valid");
				return;
			}
			
			String temp = "";
			int line = 1;

			for (String s : list) {
				if (line == 1) {
					temp = temp + s;
				} else {
					temp = temp + "\n" + s;
				}
				line++;
			}
			
			print("Splitting text...");
			//print(temp);
			String splitAtOpenTag[] = null;
			String splitAtCloseTag[] = null;
			
			splitAtOpenTag = temp.split("<!-- Start of Voice Text -->");
			
			if (Util.isNullObject(splitAtOpenTag)) {
				print("Could not find : <!-- Start of Voice Text --> ");
				return;
			}
			
			splitAtCloseTag = splitAtOpenTag[1]
					.split("<!-- End of Voice Text -->");
			
			if (Util.isNullObject(splitAtCloseTag)) {
				print("Could not find : End of Voice Text");
				System.exit(0);
			}

			String newContents = splitAtOpenTag[0] +
					"<!-- Start of Voice Text -->" +
					strTextToAdd +
					"<!-- End of Voice Text -->" +
					splitAtCloseTag[1];
			
			
			BufferedWriter bw = null;
			bw = new BufferedWriter(new FileWriter(HTML_FILE));
			bw.write(newContents);
			bw.close();

		} catch (Exception ex) {
			print(ex.toString());
		}
	}

	/**
	 * 
	 * @param line
	 * @return true if line is HTML tag
	 */
	/*static boolean isHTML(String line) {
		line = line.trim();

		if (line.equals("<p>")) {
			return true;
		} else if (line.equals("</p>")) {
			return true;
		} else if (line.endsWith("</h1>") || line.endsWith("</h2>")
				|| line.endsWith("</h3>")
				|| line.endsWith("<div class=\"lesson\">")
				|| line.endsWith("</p>")) {
			return true;
		}

		return false;
	}*/

	static void print(String msg) {
		System.out.println(msg);
	}
	
	static void print(List<String> text) {
		for (String s: text){
			System.out.println(s);
		}
	}
}
